package ua.kharkov.knure.mikhaylov.st4.settings;

import java.util.HashMap;
import java.util.Map.Entry;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;

import ua.kharkov.knure.mikhaylov.st4.db.entities.Valuta;
import ua.kharkov.knure.mikhaylov.st4.db.management.DBManager;

/**
 * A class to store necessary data. Stores valutas (duplicated to appcontext)
 * 
 * @author Saint
 * 
 */
public class DataStore {

	private static final Logger log = Logger.getLogger(DataStore.class);

	private static HashMap<Long, Valuta> valutas;

	public static HashMap<Long, Valuta> getValutas() {
		return valutas;
	}

	public static Valuta extractValuta(String shortName) {
		for (Entry<Long, Valuta> e : valutas.entrySet()) {
			if (((Valuta) e.getValue()).getShortName().equals(shortName))
				return (Valuta) e.getValue();
		}
		return null;
	}

	/**
	 * Sets the valutas to servlet context
	 * 
	 * @param sc - servlet context
	 */
	public static void initServletContext(ServletContext sc) {
		sc.setAttribute("valutas", valutas);
	}

	static {
		log.debug("Initializing valutas");
		valutas = new HashMap<Long, Valuta>();
		for (Valuta v : DBManager.getInstance().findAllValutas()) {
			valutas.put(v.getId(), v);
		}
		log.debug("Valutas were successfully initialized");
		log.trace("Number of valutas --> " + valutas.size());
		log.debug("DataStore was completely initialized");
	}
}
